# -*- coding: utf-8 -*-
import pandas as pd
import datetime

from sklearn.preprocessing import LabelEncoder

from project.src import feature_engineering
from project.utils.log import Logger
from sklearn.metrics import classification_report
import joblib
import matplotlib.pyplot as plt
import warnings

#  忽略警告
warnings.filterwarnings("ignore", module='sklearn')
#  中文字体及大小
plt.rcParams['font.family'] = 'SimHei'
plt.rcParams['font.size'] = 15

def preprocess_data(file_path):
    # df = pd.read_csv(file_path)
    df = pd.read_csv("../data/raw/test2.csv")
    # 检查缺失值
    if df.isnull().sum().any():
        print("\n发现缺失值，正在填充...")
        df.fillna(method='fill', inplace=True)

    # 提取特征与标签
    df = df.drop(['EmployeeNumber', 'Over18', 'StandardHours'], axis=1)
    # y = df['Attrition']

    # 对类别型变量进行编码
    categorical_cols = df.select_dtypes(include=['object']).columns
    for col in categorical_cols:
        le = LabelEncoder()
        df[col] = le.fit_transform(df[col])

    return df

def prediction_plot(data):

    # data有两列以上，包括真实值与预测值
    # 混淆矩阵
    pred_obj.logfile.info("模型评估")
    from sklearn.metrics import confusion_matrix,confusion_matrix, precision_score, recall_score, f1_score,roc_auc_score
    y_test = data['真实值']

    # 定义标签名
    df_label = ['未流失（正例）', '流失（反例）']

    # 定义 预测结果
    y_pre = data['预测值']
    cm_A = confusion_matrix(y_test, y_pre)
    df_A = pd.DataFrame(cm_A, index=df_label, columns=df_label)
    print(f'预测结果对应混淆矩阵为：\n{df_A}')
    pred_obj.logfile.info(f"混淆矩阵为：\n{df_A}")

    # 打印预测的 精确率、召回率、F1值

    # print(f'预测结果的精确率{precision_score(y_test, y_pre, pos_label=1)}')
    # print(f'预测结果召回率{recall_score(y_test, y_pre, pos_label=1)}')
    # print(f'预测结果的F1值{f1_score(y_test, y_pre, pos_label=1)}')
    # 打印预测报告
    print(f'预测结果的报告\n{classification_report(y_test, y_pre)}')
    pred_obj.logfile.info(f"预测结果的报告{classification_report(y_test, y_pre)}")
    #  打印AUC值
    roc_auc = roc_auc_score(y_test, y_pre)
    print(f'预测结果的AUC值{roc_auc}')
    pred_obj.logfile.info(f"预测结果的AUC值{roc_auc}")

class PowerLoadPredict(object):
    def __init__(self, filename):
        # 配置日志记录
        logfile_name = "predict_" + datetime.datetime.now().strftime('%Y%m%d%H%M%S')
        self.logfile = Logger('../../', logfile_name).get_logger()
        # 获取数据源
        self.data_source = preprocess_data(filename)


if __name__ == '__main__':
    # 1.提取数据源
    pred_obj = PowerLoadPredict("../data/raw/test2.csv")
    data = pred_obj.data_source
    data.info()

    # 2.特征提取
    preprocess_data, feature_cols = feature_engineering.feature_engineering(pred_obj.data_source, pred_obj.logfile)
    preprocess_data.info()
    # 3.加载模型
    model = joblib.load('../model/xgb.pkl')
    pred_obj.logfile.info(f"加载模型{model}")
    # 4.模型预测
    pred_obj.logfile.info("模型预测")
    y = preprocess_data['Attrition']
    X = preprocess_data[feature_cols].values
    print(len(X))
    y_pre = model.predict(X)
    # 5.模型评估
    pred_obj.logfile.info("模型评估")
    prediction_plot(pd.DataFrame({'真实值': y, '预测值': y_pre}))

